package org.example;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;

public class serivce {
    private String id;
    private int num;

    public serivce(String id, int num) {
        this.id = id;
        this.num = num;
    }

    public void service(){
        Jedis jedis = new Jedis("localhost",6379);
        String value = jedis.get("compid:"+id);
        try {
            if (value == null) {
//            jedis.set("compid:"+id,"10");
                jedis.setex("compid:"+id,20,Long.MAX_VALUE-num+"");
            }
            else {
                long val=jedis.incr("compid:"+id);
                business(num-(Long.MAX_VALUE-val));
            }
        }
        catch (JedisDataException e) {
            System.out.println("用户"+id+"调用次数已经上限，请升级");
        }
        finally {
            jedis.close();
        }

    }

    public void business(long val){
        System.out.println("用户"+id+"发起业务调用，当前是"+val+"次");
    }
}
class My_Thread extends Thread{
    serivce sc;

    public My_Thread(String id,int num){
        sc = new serivce(id, num);
    }


    public void run(){
        while(true){
//            sc.business();
            sc.service();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}